<?php
namespace App\Controller;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Job\RugbyArticleJob;
use Hyperf\Logger\LoggerFactory;
use App\Service\RugbyArticleService;

/**
 * @Controller(prefix="api/rugby")
 */
class RugbyController
{
    protected $response;
    protected $queue;
    protected $loggerFactory;

    /**
     * @var RugbyArticleService
     */
    protected $rugbyArticleService;

    public function __construct(
        HttpResponse $response,
        DriverFactory $driverFactory,
        LoggerFactory $loggerFactory
    ) {
        $this->response = $response;
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
    }

    /**
     * @GetMapping(path="rugby-article")
     */
    public function rugbyArticle(RequestInterface $request): ResponseInterface
    {
        try {
            $getData = $request->all();
            $webname = trim($getData['webname'] ?? '');

            if (empty($webname) || !is_string($webname)) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '参数 webname 必填，且为字符串'
                ]);
            }

            $conn = Db::connection($webname);
            $total = 0;

            //全部商品写文章
            $cursor = $conn->cursor("SELECT product_id FROM oc_product WHERE status = 1");

//            //单个商品写文章
//            $cursor = $conn->cursor("SELECT
//                    p.product_id,
//                    pd.name AS product_name,
//                    p.image,
//                    pd.tag,
//                    pd.description,
//                    pd.meta_title,
//                    pd.meta_description
//                FROM oc_product p
//                JOIN oc_product_description pd
//                    ON p.product_id = pd.product_id
//                LIMIT 10");

            foreach ($cursor as $product) {
                $this->queue->push(new RugbyArticleJob((int)$product->product_id, $getData, $this->loggerFactory));
                $total++;
            }

            return $this->response->json([
                'code' => 200,
                'msg' => "已推送{$total}条任务到队列",
            ]);




//            //测试的单个商品代码
//            $getData = $request->all();
//            $webname = trim($getData['webname'] ?? '');
//            $conn = Db::connection($webname);
//
//            $cursor = $conn->cursor("SELECT
//                    p.product_id,
//                    pd.name AS product_name,
//                    p.image,
//                    pd.tag,
//                    pd.description,
//                    pd.meta_title,
//                    pd.meta_description
//                FROM oc_product p
//                JOIN oc_product_description pd
//                    ON p.product_id = pd.product_id
//                WHERE p.product_id = :pid LIMIT 1",['pid' => 1306]);
//
//            $products_data = $article_data = [];
//            $articleService = ApplicationContext::getContainer()->get(RugbyArticleService::class);
//            foreach ($cursor as $product) {
//                $generateArticle_data = [
//                    'name' => $product->product_name,
//                    'description' => strip_tags(html_entity_decode($product->description)),
//                    'meta_title' => $product->meta_title,
//                    'meta_description' => $product->meta_description,
//                    'tags' => $product->tag,
//                    'keywords' => trim($this->getData['keywords'] ?? ''),
//                    'webname' => $webname,
//                    'images' => "https://www.".filter_var($webname, FILTER_SANITIZE_URL)."/image/".filter_var($product->image, FILTER_SANITIZE_URL),
//                    'url' => "https://www.".filter_var($webname, FILTER_SANITIZE_URL)."/index.php?route=product/product&product_id=".filter_var($product->product_id, FILTER_SANITIZE_NUMBER_INT)
//                ];
//                $products_data[] = $generateArticle_data;
//
//                $article = $articleService->generateArticle($generateArticle_data);
//                $article_data[] = $article;
//            }
//
//            return $this->response->json([
//                'code' => 200,
//                'products_data' => $products_data,
//                'article_data' => $article_data,
//                'web'=>$webname
//            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
}
